package com.ssm.sport.controller;

import com.ssm.sport.entity.Order;
import com.ssm.sport.entity.Shipping;
import com.ssm.sport.entity.User;
import com.ssm.sport.service.CartService;
import com.ssm.sport.service.OrderService;
import com.ssm.sport.service.ShippingService;
import com.ssm.sport.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

@Controller
public class CheckoutController {

    @Autowired
    private CartService cartService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ShippingService shippingService;

    @PostMapping("/checkout")
    @ResponseBody
    public Map<String, Object> checkout(@RequestBody Map<String, List<Integer>> request, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取用户ID
        User user = (User) session.getAttribute("user");
        if (user == null) {
            result.put("success", false);
            result.put("redirect", "/login");
            return result;
        }

        try {
            // 获取已选中的购物车商品
            List<CartVO> cartItems = cartService.getCheckedCartItems(user.getId());
            if (cartItems.isEmpty()) {
                result.put("success", false);
                result.put("message", "请选择要结算的商品");
                return result;
            }

            // 获取用户默认收货地址
            Integer shippingId = null;
            Shipping defaultShipping = shippingService.getDefaultShipping(user.getId());
            if (defaultShipping != null) {
                shippingId = defaultShipping.getId();
            } else {
                // 如果没有默认地址，获取第一个地址
                List<Shipping> shippingList = shippingService.getByUserId(user.getId());
                if (!shippingList.isEmpty()) {
                    shippingId = shippingList.get(0).getId();
                }
            }

            if (shippingId == null) {
                result.put("success", false);
                result.put("message", "请先添加收货地址");
                result.put("redirect", "/shipping/add");
                return result;
            }

            // 创建订单
            Order order = orderService.createOrder(user.getId(), shippingId);

            // 清空购物车中已结算的商品
            cartService.clearCart(user.getId());

            // 返回成功响应
            result.put("success", true);
            result.put("orderNo", order.getOrderNo());
            return result;

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "结算失败：" + e.getMessage());
            return result;
        }
    }
} 